package com.chenxing.filter;

import com.alibaba.fastjson.JSONObject;
import com.chenxing.pojo.Result;
import com.chenxing.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@WebFilter(urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;

        String url = req.getRequestURL().toString();
        log.info("请求的url:{}",url);

        if(url.contains("login")) {
            log.info("登录操作，放行...");
            chain.doFilter(request, response);
            return;
        }

        String jwt = req.getHeader("token");

        // 令牌不存在返回“未登录“
        if(!StringUtils.hasLength(jwt)) {
            log.info("请求头token为空，返回未登录的信息");
            Result error = Result.error("NOT_LOGIN");
            // object转换为json
            String notLogin = JSONObject.toJSONString(error);
            return;
        }

        // 令牌校验错误返回”token已过期或者不正确“
        try {
            JwtUtils.parseJWT(jwt);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("解析令牌失败，返回未登录错误信息");
            Result error = Result.error("NOT_LOGIN");
            String noLogin = JSONObject.toJSONString(error);
            // 将信息直接返回给前端
            resp.getWriter().write(noLogin);
            return;
        }

        log.info("令牌合法，放行");
        chain.doFilter(request, response);
    }
}
